<template>
  <topCard queryName="商品名" @SearchInput="getSearchInput" @reset="reset"/>
  <el-card class="bottomCard" v-loading="loading">
    <el-button @click="addDrawer" type="primary">添加商品</el-button>
    <el-button
      type="danger"
      @click="deleteItem(selectArr)"
      :disabled="!selectArr.length"
    >
      批量删除
    </el-button>
    <el-table
      class="bottom-table"
      border
      :data="goodsList"
      @selection-change="selectChange"
    >
      <el-table-column align="center" type="selection" width="55" />
      <el-table-column
        show-overflow-tooltip
        label="商品名称"
        align="center"
        property="goodsname"
      />
      <el-table-column
        show-overflow-tooltip
        label="商品描述"
        align="center"
        property="describe"
      />
      <el-table-column align="center" label="商品图片">
        <template #default="scope">
          <el-avatar
            :size="50"
            :src="'http://localhost:3000' + scope.row.avatar"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template #default="scope">
          {{ formatDateTime(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center">
        <template #default="scope">
          {{ formatDateTime(scope.row.updatedAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="260" align="center">
        <template #default="scope">
          <div class="tags">
            <el-tag @click="editItem(scope.row)">编辑</el-tag>
            <el-tag type="danger" @click="deleteItem(scope.row._id)">
              删除
            </el-tag>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <Pagination
      :pagination="pagination"
      :handleCurrentChange="handleCurrentChange"
      :handleSizeChange="handleSizeChange"
    />
  </el-card>
  <!-- 抽屉 -->
  <el-drawer
    class="drawer"
    v-model="drawer"
    :title="goodsParams._id ? '修改商品' : '增加商品'"
    size="26%"
    :before-close="handleClose"
  >
    <el-form label-width="100px" size="large" ref="subUserFormRef">
      <el-form-item label="商品名称" prop="username">
        <el-input placeholder="请输入商品名" v-model="goodsParams.goodsname" />
      </el-form-item>
      <el-form-item label="商品描述" prop="username">
        <el-input placeholder="请输入描述" v-model="goodsParams.describe" />
      </el-form-item>
      <el-form-item label="商品图片" prop="avatar">
        <el-upload
          class="avatar-uploader"
          action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="handleChange"
        >
          <img v-if="goodsParams.avatar" :src="uploadAvatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="subGoodsParams">提交</el-button>
      <el-button @click="drawer = false">取消</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import topCard from '@/components/topCard/index.vue'
import Pagination from '@/components/Pagination/index.vue'
import { ElMessageBox, ElForm, ElMessage } from 'element-plus'
import { formatDateTime } from '@/utils/utils'
let loading = ref(false)
//分页器
interface typePagination {
  currentPage: number
  pageSize: number
  total: number
}
const pagination: typePagination = reactive({
  pageSize: 7,
  currentPage: 1,
  total: 0,
})
let inputGoods = ref("")
//input
const getSearchInput = (input: string) => {
  inputGoods.value = input
  getGoodsList()
}
const reset = ()=>{
  inputGoods.value = ""
  getGoodsList()
}
onMounted(async () => {
  getGoodsList()
})
//获取数据
let goodsList = ref<any>([])
import { paginatedGoodsinfolist } from '@/api/goods/index'
const getGoodsList = async () => {
  try {
    loading.value = true // 开始加载
    let res = await paginatedGoodsinfolist(
      pagination.currentPage,
      pagination.pageSize,
      inputGoods.value,
    )
    if (res.code == 200) {
      pagination.total = res.total
      goodsList.value = res.data
    }
  } catch (error) {
    console.error(error) // 处理错误
  } finally {
    loading.value = false // 无论成功或失败，都结束加载
  }
}
//图片
//计算是否是展示哪一种图片
const uploadAvatar = computed(() => {
  return goodsParams.avatar.includes('blob')
    ? goodsParams.avatar
    : 'http://localhost:3000' + goodsParams.avatar
})

//抽屉相关
import { addgoods, updategoods } from '@/api/goods'
let drawer = ref(false)
interface typeGoodsParams {
  goodsname: string
  avatar: string
  describe: string
  file: string
  [i: string]: string | any // 索引签名
}
const goodsParams: typeGoodsParams = reactive({
  goodsname: '',
  avatar: '',
  describe: '',
  file: '',
  id: '',
})
//编辑
const editItem = (row: object) => {
  drawer.value = true
  Object.assign(goodsParams, row)
}
//关闭抽屉
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('确定退出提交吗?')
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
}
//提交抽屉数据
const subGoodsParams = async () => {
  const params = new FormData()
  for (let i in goodsParams) {
    params.append(i, goodsParams[i])
  }
  let res
  try {
    if (params.get('_id')) {
      res = await updategoods(params)
      if (res.code == 200) {
        drawer.value = false
        ElMessage.success('修改成功')
        Object.keys(goodsParams).forEach((key) => {
          goodsParams[key] = ''
        })
      }
    } else {
      res = await addgoods(params)
      if (res.code == 200) {
        drawer.value = false
        ElMessage.success('添加成功')
        Object.keys(goodsParams).forEach((key) => {
          goodsParams[key] = ''
        })
      }
    }
    await getGoodsList()
  } catch (error) {
    ElMessage.error('操作失败')
    console.error(error)
  }
}
//添加
const addDrawer = () => {
  goodsParams.goodsname = ''
  goodsParams.avatar = ''
  goodsParams.describe = ''
  goodsParams.file = ''
  goodsParams.id = ''
  goodsParams._id = ""
  drawer.value = true
}

// 选择头像回调
const handleChange = (file: any) => {
  //本地回显
  goodsParams.avatar = URL.createObjectURL(file.raw)
  //传给后端
  goodsParams.file = file.raw
}
//复选框发生改变
const selectArr = ref([])
const selectChange = (val: any) => {
  selectArr.value = val
}

//分页器
const handleCurrentChange = async (page: number) => {
  pagination.currentPage = page
  await getGoodsList()
}
const handleSizeChange = async (limit: number) => {
  pagination.pageSize = limit
  await getGoodsList()
}

//删除数据
import { deletegoods } from '@/api/goods'
const deleteItem = async (id: number | Array<any>) => {
  let queryParams = ''
  let selectId = []
  if (Array.isArray(id)) {
    selectId = id.map((i) => {
      return i._id
    })
  }
  queryParams = selectId.map((id) => `id=${id}`).join('&') ?? id
  try {
    const res = await deletegoods(queryParams)
    if (res.code == 200) {
      getGoodsList()
      ElMessage.success('删除成功')
    }
  } catch (error) {
    ElMessage.error('删除失败')
    console.error(error)
  }
}
</script>

<style lang="scss" scoped>
.bottomCard {
  .bottom-table {
    margin: 10px 0;
    width: 100%;
    .tags {
      display: flex;
      align-items: center;
      justify-content: center;
      .el-tag {
        cursor: pointer;
        margin: 0 6px;
      }
    }
  }
}
// 右侧抽屉
.drawer {
  .el-form-item {
    margin-bottom: 24px;
  }
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
